package com.huike.handler;

import com.huike.constant.HttpStatus;
import com.huike.core.domain.AjaxResult;
import com.huike.exception.BaseException;
import com.huike.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 全局异常处理器，处理项目中抛出的业务异常
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
    /**
     * 捕获业务异常
     * @param ex
     * @return
     */
    @ExceptionHandler
    public Result exceptionHandler(BaseException ex){
        log.error("异常信息：{}", ex.getMessage());
        return Result.error(ex.getMessage());
    }

    @ExceptionHandler(DuplicateKeyException.class)
    public ResponseEntity<AjaxResult> handleDuplicateKey(DuplicateKeyException ex) {
        String message = "数据重复：" + extractDuplicateField(ex.getMessage());
        return ResponseEntity.status(HttpStatus.SUCCESS).body(AjaxResult.error(HttpStatus.CONFLICT,
                message));
    }
    private String extractDuplicateField(String errorMsg) {
        // 解析错误信息提取重复字段名
        Pattern pattern = Pattern.compile("key '(.+?)'");
        Matcher matcher = pattern.matcher(errorMsg);
        return matcher.find() ? matcher.group(1) : "未知字段";
    }
}
